package com.ling.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.ling.bean.*;
import com.ling.dto.RecommendationDto;
import com.ling.service.*;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class RecommendController {
    private final SubscribeService subscribeService;
    private final UserTrackService userTrackService;
    private final ElasticSearchService elasticSearchService;
    private final BlogService blogService;
    private final QuestionService questionService;
    private final AreaService areaService;

    @Autowired
    public RecommendController(SubscribeService subscribeService, UserTrackService userTrackService, ElasticSearchService elasticSearchService, BlogService blogService, QuestionService questionService, AreaService areaService) {
        this.subscribeService = subscribeService;
        this.userTrackService = userTrackService;
        this.elasticSearchService = elasticSearchService;
        this.blogService = blogService;
        this.questionService = questionService;
        this.areaService = areaService;
    }

    @GetMapping("/recommend")
    public String goToRecommend() {
        return "recommend";
    }

    @GetMapping("/saveSubscribe/{week}")
    @ResponseBody
    public Msg saveSubscribe(HttpSession session, @PathVariable Integer week) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请重新登录！");
        }
        Subscribe subscribe = new Subscribe();
        subscribe.setId(StringUtil.getRandomString(16));
        subscribe.setUserid(user.getId());
        subscribe.setWeek(week);
        if (subscribeService.existRecord(user.getId())) {
            return Msg.fail().add("error", "您已经订阅过邮件服务，请不要重复订阅。");
        }
        subscribeService.saveSubscribe(subscribe);
        return Msg.success();
    }

    @GetMapping("/getRecommendation")
    @ResponseBody
    public Msg getRecommendation(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            PageHelper.startPage(1, 4);
            List<UserTrack> userTrackByUserId = userTrackService.getUserTrackByUserId(user.getId());
            //循环usertrack查询
            String key;
            HashMap<String, RecommendationDto> hashMap = new HashMap<>();
            for (UserTrack userTrack : userTrackByUserId) {
                if (userTrack.getType()) {
                    //blog
                    Blog blogById = blogService.getBlogById(userTrack.getTypeid());
                    key=areaService.getArea(blogById.getAreaid()).getAreaname();
                }else{
                    Question userQuestionById = questionService.getUserQuestionById(userTrack.getTypeid());
                    key = areaService.getArea(userQuestionById.getAreaid()).getAreaname();
                }
                ResponseEntity<String> responseEntityByTitle = elasticSearchService.getRecommendationByTitle(key);
                ResponseEntity<String> responseEntityByContent = elasticSearchService.getRecommendationByContent(key);
                convertToRecommendationDto(responseEntityByTitle.getBody(),hashMap);
                convertToRecommendationDto(responseEntityByContent.getBody(),hashMap);
            }
            return Msg.success().add("hashMap",hashMap);
        } else {
            //未登录
            return Msg.fail().add("error","请重新登录！");
        }
    }

    private void convertToRecommendationDto(String str, Map<String, RecommendationDto> map) {
        ObjectMapper objectmapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectmapper.readTree(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert jsonNode != null;
        jsonNode = jsonNode.get("hits").get("hits");
        for (int i = 0; i < jsonNode.size(); i++) {
            JsonNode jsonNodeSub = jsonNode.get(i);
            String key = jsonNodeSub.get("_type").asText() + ":" + jsonNodeSub.get("_id").asText();
            JsonNode source = jsonNodeSub.get("_source");
            RecommendationDto recommendationDto = null;
            try {
                recommendationDto = objectmapper.readValue(source.toString(), RecommendationDto.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            map.put(key, recommendationDto);
        }
    }
}
